# http_client_enhanced.py
import requests

class MCPClient:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url

    def list_tools(self):
        """获取可用工具列表"""
        url = f"{self.base_url}/tools/list"
        try:
            response = requests.get(url, timeout=10)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"获取工具列表错误: {e}")
            return None

    def call_tool(self, tool_name, arguments):
        """调用工具"""
        url = f"{self.base_url}/tools/call"

        payload = {
            "name": tool_name,
            "arguments": arguments
        }

        try:
            response = requests.post(
                url,
                json=payload,
                timeout=30,
                headers={"Content-Type": "application/json"}
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"调用工具错误: {e}")
            try:
                print("响应内容:", response.text)
            except:
                pass
            return None

    def health_check(self):
        """健康检查"""
        url = f"{self.base_url}/health"
        try:
            response = requests.get(url, timeout=5)
            return response.status_code == 200
        except:
            return False

def main():
    client = MCPClient()

    print("🏥 检查服务器健康状态...")
    if client.health_check():
        print("✅ 服务器健康")
    else:
        print("❌ 服务器不可用")
        return

    print("\n🛠️ 获取工具列表...")
    tools = client.list_tools()
    if tools:
        print("可用工具:")
        for tool in tools.get('tools', []):
            print(f"  - {tool['name']}: {tool['description']}")
    else:
        print("无法获取工具列表")
        return

    # 测试工具调用
    test_cases = [
        ("generate_rag_output", {"query": "什么是机器学习？"}),
        ("run_web_search", {"query": "人工智能的最新发展"}),
        ("list_indexed_documents", {})
    ]

    for tool_name, arguments in test_cases:
        print(f"\n🔧 测试 {tool_name}...")
        result = client.call_tool(tool_name, arguments)
        if result and result.get('success'):
            print(f"✅ 成功: {result.get('result')}")
        else:
            print(f"❌ 失败: {result}")

if __name__ == "__main__":
    main()